'use client'
import {
   MenuFoldOutlined,
   HomeOutlined,
   PoweroffOutlined,
   MenuUnfoldOutlined,
   FileOutlined,
   DownOutlined,
   UserOutlined,
   BookOutlined,
} from '@ant-design/icons';
import { Layout, Menu, Dropdown, MenuProps, Button, message, Popconfirm, Input, Table, Select } from 'antd';
import type { TableColumnsType, PopconfirmProps } from 'antd';
import React, { useState, ChangeEvent, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation'
import Link from 'next/link';
import { getCookie } from '../utils'
interface favType {
   ttid: number,
   ttname: string
}
interface SelectItem {
   label: string,
   value: string;
}
const { Header, Sider, Content } = Layout;


const confirm: PopconfirmProps['onConfirm'] = (e) => {
   message.success('Click on Yes');
};

const cancel: PopconfirmProps['onCancel'] = (e) => {
   console.log(e);
   message.error('Click on No');
};

const DocMgt: React.FC = () => {
   const [collapsed, setCollapsed] = useState(false);
   const [showName, setShowName] = useState(false);
   const [iputVal, setIputVal] = useState('');
   const [showRenameBtn, setShowRenameBtn] = useState(false);
   const [showDelTypeBtn, setShowDelTypeBtn] = useState(false);
   const [rename, setRename] = useState('重命名该类别');
   const [selectedValue, setSelectedValue] = useState('');
   const [selectList, setSelectList] = useState<SelectItem[]>([])
   const [username, setUsername] = useState('');

   interface DataType {
      toid: number,
      tofrom: string;
      tohref: string;
      tolink: string;
      toname: string,
      totime: string;
   }

   const handleDelete = (id: number) => {
      fetch('/SWJDTXT/queryTodelete.action?toid=' + id, { method: 'POST' }).then(res => {
         res.text().then(datas => {
            if (datas == '成功') {
               message.success('删除成功');
               fetchTableData(selectedValue.split('-')[1])
            } else {
               message.error('删除失败！')
            }
         })
      })
   };
   const columns: TableColumnsType<DataType> = [
      {
         title: '文献名称',
         dataIndex: 'toname',
         key: 'toname',
         width: 300,
         fixed: 'left',
      },
      {
         title: '链接',
         width: 80,
         dataIndex: 'tolink',
         key: 'tolink',
         render: (_, record) => {
            if (record.tolink.indexOf('http') == 0) {
               return <a className='text-blue-500' target='_blank' href={record.tolink}>链接</a>
            } else {
               return '暂无链接'
            }
         },
      },
      {
         title: '文献来源',
         dataIndex: 'tohref',
         key: 'tohref',
         width: 150,
      },
      {
         title: '网站',
         dataIndex: 'tofrom',
         key: 'tofrom',
         width: 150,
      },
      {
         title: '收藏时间',
         dataIndex: 'totime',
         key: 'totime',
         width: 150,
      },
      {
         title: '操作',
         key: 'operation',
         fixed: 'right',
         width: 100,
         render: (_, record) => <Popconfirm
            title="删除提示"
            description="你确定要删除这个收藏吗?"
            onConfirm={() => handleDelete(record.toid)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
         >
            <Button type='primary' danger>删除</Button>
         </Popconfirm>,
      },
   ];
   const [data, setData] = useState<DataType[]>();
   useEffect(() => {
      let username = getCookie('sjhm');
      // if (username == '') {
      //    window.location.href="https://www.xsjxkt.com/qd/dl/login"
      //    message.warning('请首先登录！');
      //    return () => { }
      // }
      setUsername(username);
      async function fetchData() {
         // const response = await fetch('/SWJDTXT/queryTtpeo.action?ttpeople=13207192878', { method: 'POST' });
         const response = await fetch('/SWJDTXT/queryTtpeo.action?ttpeople=' + username, { method: 'POST' });
         const fetchedDatas = await response.json();
         let serverSelList = fetchedDatas.map((item: favType) => {
            return { label: item.ttname, value: item.ttid + '-' + item.ttname }
         })
         setSelectList(serverSelList)
      }
      fetchData();
      return () => {
         // 组件即将卸载，这里可以做一些清理工作，如取消请求等
      };
   }, []);
   const fetchTableData = (label: string) => {
      // 获取表格的数据
      // fetch('/SWJDTXT/queryTotype.action?toman=13207192878' + '&totype=' + label, { method: 'POST' }).then(res => {
      fetch('/SWJDTXT/queryTotype.action?toman=' + username + '&totype=' + label, { method: 'POST' }).then(res => {
         res.json().then(datas => {
            setData(datas)
         })
      })
   }
   const handleSelChange = (value: string) => {
      setSelectedValue(value)
      let label = value.split('-')[1]
      // 重命名start
      // 回归最初的状态
      setRename('重命名该类别')
      setShowName(false)
      // 设置默认值
      setIputVal(label)
      // 重命名end
      fetchTableData(label)
   };
   const handleRename = () => {
      if (rename == '重命名该类别') {
         setShowName(true)
         setRename('确定该名称')
         // 这里做异步的处理
      } else {
         setTimeout(() => {
            setRename('重命名该类别')
            setShowName(false)
         }, 3000)
      }
   }
   const changeInputVal = (event: ChangeEvent<HTMLInputElement>) => {
      setIputVal(event.target.value);
   };
   const handleDeleteSel = (id: number) => {
   }
   const router = useRouter()
   function onClick(obj: { key: string }) {
      if (obj.key === '1') {
         // 跳转到官网
      } else {
         // 退出登录
      }
   };
   const onClickMenu: MenuProps['onClick'] = e => {
      if (e.key == '11') {
         // 跳转到用户信息-我的信息页面
         router.push('/user')
      } else if (e.key == '31') {
         // 跳转到自定义数据集-数据集社区页面
         router.push('/dataClub')
      } else if (e.key == '32') {
         // 跳转到自定义数据集-已选数据集页面
         router.push('/dataChosen')
      }
   };
   const items = [{
      key: '1',
      label: (
         <Link href="https://www.xsjxkt.com">
            <HomeOutlined /><span style={{ marginLeft: 6 }}>回到官网</span>
         </Link>
      ),
   }, {
      key: '2',
      label: (
         <div><PoweroffOutlined /><span style={{ marginLeft: 6 }}>退出登录</span></div>
      ),
   }]

   return (
      <Layout style={{ height: '100%' }}>
         <Sider style={{ backgroundColor: '#f5f5f5' }} trigger={null} collapsible collapsed={collapsed}>
            <div className="logo" />
            <Menu style={{ backgroundColor: '#f5f5f5', border: 'none' }}
               theme="light"
               onClick={onClickMenu}
               mode="inline"
               defaultOpenKeys={['2']}
               defaultSelectedKeys={['2']}
               items={[
                  // {
                  //    key: '1',
                  //    icon: <UserOutlined />,
                  //    label: '用户信息',
                  //    children: [
                  //       {
                  //          key: '11',
                  //          label: '我的信息',
                  //       },
                  //    ]
                  // },
                  {
                     key: '2',
                     icon: <BookOutlined />,
                     label: '文献管理',
                  },
                  {
                     key: '3',
                     icon: <FileOutlined />,
                     label: '自定义数据集',
                     children: [
                        {
                           key: '31',
                           label: '数据集社区',
                        },
                        {
                           key: '32',
                           label: '已选数据集',
                        }
                     ]
                  },
               ]}
            />
         </Sider>
         <Layout className="site-layout" style={{ backgroundColor: '#fff' }}>
            <Header className="site-layout-background" style={{ backgroundColor: '#f5f5f5', paddingLeft: 12 }}>
               {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
                  className: 'trigger',
                  onClick: () => setCollapsed(!collapsed),
               })}
               <div style={{ float: 'right' }}>
                  <Dropdown menu={{ items, onClick }}>
                     <a onClick={e => e.preventDefault()}>
                        <UserOutlined /> {username}
                        <DownOutlined style={{ marginLeft: 8 }} />
                     </a>
                  </Dropdown>
               </div>
            </Header>
            <Content
               className="site-layout-background"
               style={{
                  padding: 24,
               }}
            >
               <div style={{ marginBottom: 6 }}>
                  <Select
                     value={selectedValue}
                     showSearch
                     style={{ width: 200 }}
                     placeholder="Search to Select"
                     onChange={handleSelChange}
                     optionFilterProp="label"
                     filterSort={(optionA, optionB) =>
                        (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
                     }
                     options={selectList}
                  />
                  {showName ? <Input style={{ display: 'inline-block', width: 240, marginLeft: 6 }} placeholder="Outlined" value={iputVal} onChange={changeInputVal} defaultValue="" /> : null}
                  {showRenameBtn ? <Button type="primary" style={{ margin: '0 6px' }} onClick={handleRename} autoInsertSpace>
                     {rename}
                  </Button> : null}
                  {showDelTypeBtn ? <Popconfirm
                     title="删除类别"
                     description="你确定要删除这个类别吗?"
                     onConfirm={confirm}
                     onCancel={cancel}
                     okText="Yes"
                     cancelText="No"
                  >
                     <Button type='primary' danger>删除该类别</Button>
                  </Popconfirm> : null}
                  {/* <Button type="primary" style={{ background: '#008000', marginLeft: 6 }} autoInsertSpace>
                     新增文献
                  </Button>
                  <Button type="primary" style={{ marginLeft: 6 }} autoInsertSpace>
                     导出文献
                  </Button> */}
               </div>
               <Table
                  size="small"
                  columns={columns}
                  dataSource={data}
                  rowKey={(record) => record.toid}
                  scroll={{ x: 1500 }}
                  sticky={{ offsetHeader: 64 }}
               />
            </Content>
         </Layout>
      </Layout>
   );
};

export default DocMgt;